package com.totoro.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.pojo.Address;
import com.totoro.pojo.BuyShop;
import com.totoro.pojo.MyHistory;
import com.totoro.pojo.User;
import com.totoro.service.AddressService;
import com.totoro.service.ProductService;
import com.totoro.service.ShopService;
import com.totoro.service.UserService;
import com.totoro.utils.ReturnFormat;
import lombok.SneakyThrows;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/7/2 9:02
 * 用户处理控制器
 */
@Controller
@RequestMapping("/user_logic")
public class UserCenterController {
    @Autowired
    AddressService addressService;
    @Autowired
    UserService userService;
    @Autowired
    ProductService productService;
    @Autowired
    private ShopService shopService;
    private HttpSession session;

    @ResponseBody
    @RequestMapping(value = "/userStatus", method = RequestMethod.POST)
    public String isLogin(HttpSession session){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "no";
        }
        return "yes";
    }

    /**
     * 是否有该用户名称，与注册的不同
     * @param name
     * @param session
     * @return
     */
    @RequestMapping(value = "/isHaveUserName", method = RequestMethod.POST)
    @ResponseBody
    public String isHaveUserName(@RequestParam("name") String name, HttpSession session){
        User selfUser = (User) session.getAttribute("user");
        // 最新User
        User newUser = userService.findUserById(selfUser.getUserId());
        System.out.println(newUser.getUserName().equals(name));
        if(newUser.getUserName().equals(name)){
            return "ok";
        }
        List<User> users = userService.userNameTest(name);
        System.out.println(users.size());
        if(users != null || users.size()>0){
            return "no";
        }
        return "ok";
    }

    /**
     * 保存用户输入的个人信息
     * @param file
     * @param user
     * @param request
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/saveData", method = RequestMethod.POST)
    public String saveUserData(MultipartFile file, User user, HttpServletRequest request, HttpSession session){
        Thread.sleep(1500);
        return userService.saveUserDataByUid(file, user, request, session);
    }

    /**
     * 添加新地址
     * @param address
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/insert_address", method = RequestMethod.POST)
    public String insertAddress(Address address, HttpSession session){
        User user = (User) session.getAttribute("user");
        address.setUid(user.getUserId());
        System.out.println(address);
        Thread.sleep(2500);
        addressService.addAddress(address);
        // 如果用户选择了该新地址为默认，那么取消他的其他地址默认效果
        if(address.getDefaultAddress() == 1){
            addressService.updateAddressNotDefaultByUidAndAid(user.getUserId(), addressService.getAddressLength());
        }
        return "redirect:/user/receiptAddress.htm";
    }

    /**
     * 修改地址
     * @param address
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "update_address", method = RequestMethod.POST)
    public String updateAddress(Address address, HttpSession session){
        User user = (User) session.getAttribute("user");
        // 获取当前地址 aid
        int aid = address.getId();
        addressService.updateAddressByAid(address);
        // 如果用户选择了该地址为默认，那么取消他的其他地址默认效果
        if(address.getDefaultAddress() == 1){
            addressService.updateAddressNotDefaultByUidAndAid(user.getUserId(), aid);
        }
        return "redirect:/user/receiptAddress.htm";
    }

    /**
     * 删除地址
     * @param addrId
     * @return
     */
    @SneakyThrows
    @RequestMapping("/delete_address")
    @ResponseBody
    public String deleteAddress(@RequestParam("addrId") int addrId){
        addressService.deleteAddress(addrId);
        Thread.sleep(1000);
        return "T O T O R O";
    }

    /**
     * 将某个用户 & 某个地址设为默认
     * @param addrId
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/set_address_default", method = RequestMethod.POST)
    public String setDefault(@RequestParam("addrId") int addrId, HttpSession session){
        User user = (User) session.getAttribute("user");
        int uid = user.getUserId();
        // 将该aid对应的记录设为默认
        addressService.updateAddressNotDefaultByUidAndAid(uid, addrId);
        addressService.updateAddressIsDefaultByAid(addrId);
        Thread.sleep(1000);
        return "redirect:/user/receiptAddress.htm";
    }

    /**
     * 不跳转 -- 设置默认，这个是iframe中的
     * @param addrId
     * @param session
     * @return
     */
    @SneakyThrows
    @ResponseBody
    @RequestMapping(value = "/setAddrDefault", method = RequestMethod.POST)
    public String setDefaultNoJump(@RequestParam("addrId") int addrId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        int uid = user.getUserId();
        // 将该aid对应的记录设为默认
        addressService.updateAddressNotDefaultByUidAndAid(uid, addrId);
        addressService.updateAddressIsDefaultByAid(addrId);
        Thread.sleep(1000);
        return "ttr";
    }

    /**
     * 刪除一條足跡
     * @param mhId
     * @return
     */
    @RequestMapping(value = "deleteHistory", method = RequestMethod.POST)
    @ResponseBody
    public String deleteHistory(@RequestParam("mhId") int mhId){
        Integer deleteHis=userService.deleteHistory(mhId);
        return "yes";
    }

    /**
     * 获取购买过的足迹数据 流加载+分页
     * @param curr
     * @param session
     * @return
     */
    @RequestMapping(value = "findBuyShopData", method = RequestMethod.POST)
    @ResponseBody
    public String findBuyShopData(@RequestParam(value = "curr", required = false, defaultValue = "1") int curr,
                                  @RequestParam(value = "categoryId", required = false, defaultValue = "0") int categoryId,
                                  @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
                                  HttpSession session){
        User user = (User) session.getAttribute("user");
        Map<Integer,List<BuyShop>> map = productService.findAllUserBuyShop(user.getUserId(), categoryId, keyword, curr);
        // 最多展示五條
        int assignLength = 5;
        map.forEach((k,v) ->{
            if(v.size() > assignLength){
                v = v.subList(0,5);
            }
        });
        List<Object> list = new ArrayList<>();
        list.add(map);
        list.add(map.size());
        try {
            return new ObjectMapper().writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除一条购买过的店铺
     * @param sid
     * @param session
     * @return
     */
    @RequestMapping(value = "deleteBabyShop", method = RequestMethod.POST)
    @ResponseBody
    public String deleteBabyShop(@RequestParam("sid") int sid, HttpSession session){
        User user = (User) session.getAttribute("user");
        productService.deleteBuyShop(user.getUserId(), sid);
        return "success";
    }

    /**
     * 取消收藏一个店铺
     * @param sid
     * @param session
     * @return
     */
    @RequestMapping(value = "/cancelCollectShop", method = RequestMethod.POST)
    @ResponseBody
    public String cancelCollectShop(@RequestParam("sid") int sid, HttpSession session){
        User user = (User) session.getAttribute("user");
        shopService.cancelCollectShop(user.getUserId(), sid);
        shopService.updateShopCollectCount(1, sid);
        return "success";
    }

    /**
     * 批量删除店铺
     * @param clids
     * @return
     */
    @RequestMapping(value = "/batchReduceShopCollectCount", method = RequestMethod.POST)
    @ResponseBody
    public String batchReduceShopCollectCount(@RequestParam("clids[]") Integer[] clids){
        for (int i = 0; i < clids.length; i++) {
            System.err.println(clids[i]);
        }
        shopService.batchReduceShopCollectCount(clids);
        shopService.batchDeleteCollectShop(clids);
        return "success";
    }



}
